package com.hafiery.sdk.bluetooth.test;
import android.Manifest;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.hafiery.sdk.bluetooth.BlueToothActionImp;
import com.hafiery.sdk.bluetooth.IBlueToothAction;
import com.hafiery.sdk.bluetooth.IBlueToothActionListener;
import com.hafiery.sdk.bluetooth.api.BlueToothSDK;
import com.hafiery.sdk.bluetooth.test.adapter.BleListAdapter;
import com.hafiery.sdk.bluetooth.test.util.ActivityManager;
import com.hafiery.sdk.bluetooth.transport.adapter.NobodyAdapter;
import com.hafiery.sdk.bluetooth.transport.callback.CallBackHandler;
import com.hafiery.sdk.bluetooth.transport.callback.Callback;
import com.hafiery.sdk.bluetooth.transport.constant.ErrorCode;
import com.hafiery.sdk.bluetooth.transport.constant.OpCode;
import com.hafiery.sdk.bluetooth.transport.req.RequestData;
import com.hafiery.sdk.bluetooth.util.ByteUtil;
import com.hafiery.sdk.bluetooth.util.LogUtil;

import java.util.*;

public class MainActivity extends AppCompatActivity {

    private UUID[] uuid;
    private final int REQUEST_CODE_LOCATION =0x001;
    private IBlueToothAction blueToothClient;
    private LinkedHashSet<BluetoothDevice> mDatas=new LinkedHashSet<>();
    private Set<BluetoothDevice> m=new HashSet<>();
    private BleListAdapter adapter;
    Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar= findViewById(R.id.toolbar);
        toolbar.setTitle(getString(R.string.scan_title));
        setSupportActionBar(toolbar);

        String b=Long.toHexString(System.currentTimeMillis()/1000l);
        Long six = Long.parseLong(b,16);

        RecyclerView recyclerView=findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayout.VERTICAL));
        adapter=new BleListAdapter(mDatas);
        adapter.setOnItemClicklistener((item,position) -> {
            if(blueToothClient.isEnabled()){
                showConnectDialog(item);
            }else{
                Toast.makeText(MainActivity.this,"蓝牙已关闭,请重新扫描",Toast.LENGTH_SHORT).show();
            }

        });
        recyclerView.setAdapter(adapter);
        showScanFilterDialog();
    }

    private void initBle(){
        blueToothClient = BlueToothSDK.instance().getBlueToothClient();
        blueToothClient.setBlueToothActionListener(new IBlueToothActionListener() {
            @Override
            public void onStartScan() {
                Menu menu=toolbar.getMenu();
                if(menu!=null && menu.findItem(R.id.stopScan)!=null){
                    toolbar.getMenu().findItem(R.id.stopScan).setTitle(getString(R.string.stopScan));
                }
                mDatas.clear();
                adapter.notifyDataSetChanged();
            }
            @Override
            public void onScanResult(BluetoothDevice device, int rssi) {
                mDatas.add(device);
                adapter.notifyItemRangeInserted(mDatas.size(),1);
            }
            @Override
            public void onStopScan() {
                toolbar.getMenu().findItem(R.id.stopScan).setTitle(getString(R.string.reScan));

            }

            @Override
            public void onGattConnectStart(BluetoothDevice device) {
                if(connectingDialog==null){
                    connectingDialog = new ProgressDialog(MainActivity.this);
                    connectingDialog.setTitle("提示");
                    connectingDialog .setMessage("蓝牙连接中");
                    connectingDialog.setCancelable(false);
                    connectingDialog.show();
                }
                connectingDialog.show();
            }

            @Override
            public void onGattConnected(BluetoothDevice device) {
                if(connectingDialog!=null&&connectingDialog.isShowing())
                    connectingDialog.dismiss();
                Toast.makeText(MainActivity.this,getString(R.string.bluetooth_device_connected)+device.getName(),Toast.LENGTH_LONG).show();
            }
            @Override
            public void onGattConnectError(int status) {
                if(connectingDialog!=null&&connectingDialog.isShowing())
                    connectingDialog.dismiss();
                Toast.makeText(MainActivity.this,"连接工牌失败:"+status,Toast.LENGTH_LONG).show();
            }

            @Override
            public void onShakeHandsSuccess() {
                Toast.makeText(MainActivity.this,getString(R.string.shake_hands_success),Toast.LENGTH_LONG).show();
                Intent intent=new Intent(MainActivity.this,ConfigActivity.class);
                startActivity(intent);
            }

            @Override
            public void onShakeHandsFailed(ErrorCode errorCode) {
                Toast.makeText(MainActivity.this,getString(R.string.shake_hands_failed),Toast.LENGTH_LONG).show();
            }



            @Override
            public void onGattConnectDisconnect() {
                Toast.makeText(MainActivity.this,"蓝牙设备已主动断开工牌",Toast.LENGTH_LONG).show();
                Intent intent = new Intent(MainActivity.this,MainActivity.class);
                startActivity(intent);
            }

            @Override
            public void onBlueToothOpenOrCloseStatusChanged(boolean open) {
                if(open){
                    startScan();
                }else{
                    Toast.makeText(MainActivity.this,"蓝牙已关闭",Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(MainActivity.this,MainActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    private ProgressDialog connectingDialog;

    void onRequestLocationPermission(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE_LOCATION);
            }else{
                startScan();
            }
        }else{
            startScan();
        }
    }
    private void startScan(){
        blueToothClient.startScan();
    }
    private void stopScan(){
        blueToothClient.stopScan();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case REQUEST_CODE_LOCATION:
                if(grantResults.length>0&&grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    startScan();
                }else{
                    Toast.makeText(MainActivity.this,getString(R.string.permission_denied),Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    private void showConnectDialog(BluetoothDevice device){
        new AlertDialog.Builder(MainActivity.this)
                .setTitle(getString(R.string.item_dialog_title))
                .setMessage(getString(R.string.item_dialog_connect_content,device.getName()))
                .setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss())
                .setPositiveButton(getString(R.string.connect), (dialog, which) -> {
                    dialog.dismiss();
                    blueToothClient.connect(device,false);
                })
                .create()
                .show();
    }

    private void showScanFilterDialog(){
//        EditText editText = new EditText(MainActivity.this);
//        editText.setPadding(50,20,50,20);
//        editText.setText("000000ff-0000-1000-8000-00805f9b34fb");
//        editText.setText("0000b3ff-0000-1000-8000-00805f9b34fb");
//        AlertDialog alertDialog=new AlertDialog.Builder(MainActivity.this)
//                .setTitle(getString(R.string.item_dialog_title))
//                .setMessage(getString(R.string.item_dialog_filter_content))
//                .setNegativeButton(getString(R.string.skip), (dialog, which) -> {
//                    dialog.dismiss();
//                    onRequestLocationPermission();
//                })
//                .setPositiveButton(getString(R.string.confirm), (dialog, which) -> {
//                    uuid=new UUID[]{UUID.fromString(editText.getText().toString())};
//                    dialog.dismiss();
//                    onRequestLocationPermission();
//                })
//                .create();
//        alertDialog.setView(editText);
//        alertDialog.show();

        new android.app.AlertDialog.Builder(MainActivity.this)
                .setTitle("请选择工牌类型")
                .setCancelable(false)
                .setSingleChoiceItems(getResources().getStringArray(R.array.card_type), 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        switch (which){
                            case 0:
                                uuid=new UUID[]{UUID.fromString("000000ff-0000-1000-8000-00805f9b34fb")};
                                BlueToothSDK.init(new BlueToothActionImp(MainActivity.this,
                                        UUID.fromString("000000ff-0000-1000-8000-00805f9b34fb"),
                                        UUID.fromString("0000ff01-0000-1000-8000-00805f9b34fb"),
                                        UUID.fromString("0000ff01-0000-1000-8000-00805f9b34fb"),
                                        UUID.fromString("0000ff01-0000-1000-8000-00805f9b34fb")));
                                break;
                            case 1:
                                uuid=new UUID[]{UUID.fromString("0000b3ff-0000-1000-8000-00805f9b34fb")};
                                BlueToothSDK.init(new BlueToothActionImp(MainActivity.this,
                                        UUID.fromString("0000b3ff-0000-1000-8000-00805f9b34fb"),
                                        UUID.fromString("0000d6c9-0000-1000-8000-00805f9b34fb"),
                                        UUID.fromString("0000d6c9-0000-1000-8000-00805f9b34fb"),
                                        UUID.fromString("0000d1c9-0000-1000-8000-00805f9b34fb")));
                                break;
                        }
                        initBle();
                        onRequestLocationPermission();
                    }
                }).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar,menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.stopScan:
                if(blueToothClient.isScanning())
                    stopScan();
                else
                    startScan();
                break;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        stopScan();
        super.onDestroy();
    }
}
